package com.yu.juc;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author Irelia
 * @Date 2024/7/5 15:17
 * 使用 CompletableFuture.thenRunAsync 来控制线程的顺序
 */
public class CompletableFutureDemo {

    public static void main(String[] args) {
        CompletableFuture<Void> c1 = CompletableFuture.runAsync(() -> {
            System.out.println("T1 is executing after T1.Current time：" +new Date());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        // T2 在 T1 完成后执行
        CompletableFuture<Void> futureT2 = c1.thenRunAsync(() -> {
            System.out.println("T2 is executing after T1.Current time：" +new Date());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

// T3 在 T2 完成后执行
        CompletableFuture<Void> futureT3 = futureT2.thenRunAsync(() -> {
            System.out.println("T3 is executing after T2.Current time：" + new Date());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
